package com.digiproto.app_store;

import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import com.andexert.library.RippleView;
import com.digiproto.app_store.model.Game;
import com.digiproto.app_store.page.IndexFragment;
import com.isanwenyu.tabview.TabGroup;
import com.isanwenyu.tabview.TabView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cz.msebera.android.httpclient.Header;


public class MainActivity extends AppCompatActivity {
    //public static final int TAB_CHAT = 0x00;
    public static final int TAB_APP = 0x00;
    //public static final int TAB_PIC = 0x02;
    public static final int TAB_USER = 0x01;
    private static final String TAG = MainActivity.class.getSimpleName();

    @InjectView(R.id.vp_main)
    ViewPager mViewPager;
    @InjectView(R.id.tg_tab)
    TabGroup mTabGroup;
    @InjectView(R.id.tb_app)
    TabView mChatTabView;

    private FragmentManager manager;

    // 游戏数据
    private ArrayList<Game> games = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setContentView(R.layout.activity_main);
        setManager(getFragmentManager());
        // 绑定当前界面
        ButterKnife.inject(this);
        initView();
        //创建默认的ImageLoader配置参数
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration
                .createDefault(this);
        //Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(configuration);
    }

    /**
     * 初始化数据
     */
    private final void initData(){
        // 创建客户端对象
        AsyncHttpClient client = new AsyncHttpClient();
        String url = "http://www.siftgame.com:8087/gamestore/api/gameinfo";
        client.get(url,new Handler());
    }

    public static class Handler extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.e("ID","gameId");
            if(statusCode == 200){
                for(int i = 0 ; i < response.length() ; i ++){
                    try {
                        JSONObject obj = response.getJSONObject(String.valueOf(i));
                        System.out.print(obj.get("gameId"));
                        Log.e("ID",obj.getString("gameId"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 初始化布局
     */
    private void initView() {
        initViewPager();
        mTabGroup.setOnCheckedChangeListener(new TabGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(TabGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tb_app:
                        setCurrentFragment(TAB_APP);
                        break;
                    case R.id.tb_user:
                        setCurrentFragment(TAB_USER);
                        break;
                }
            }
        });

        mChatTabView
                .setBadgeColor(getResources().getColor(android.R.color.holo_blue_dark))
                .setmDefaultTopPadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()))
                .setBadgeShown(true)
                .setTabRippleCentered(false)
                .setTabRippleColor(android.R.color.holo_blue_dark)
                .setTabRippleDuration(100)
                // override setOnRippleCompleteListener method in rippleView
                .setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        mChatTabView.setChecked(true);
                    }
                });

        ((TabView) mTabGroup.getChildAt(1)).setBadgeCount(999)
                .setmDefaultTopPadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()))
                .setBadgeShown(true)
                .setTabRippleEnable(false);
    }

    /**
     * 初始化viewpager
     */
    private void initViewPager() {

        //缓存3页避免切换时出现空指针
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(new ContentFragmentAdapter.Holder(getSupportFragmentManager())
                .add(IndexFragment.newInstance(getManager(),null))
                .set());
        mViewPager.setCurrentItem(0);
        // 添加事件监听
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ((TabView) mTabGroup.getChildAt(position)).setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 改变fragment状态
     *
     * @param position
     */
    public void setCurrentFragment(final int position) {
        Log.i(TAG, "position:" + position);
        //不使用切换动画 避免与自定义动画冲突
        mViewPager.setCurrentItem(position, false);
    }

    public void setManager(FragmentManager manager) {
        this.manager = manager;
    }

    public FragmentManager getManager() {
        return manager;
    }
}
